package com.runfast.waimai.web.controller.pictureManage;

import cn.jpush.api.push.PushResult;
import com.runfast.common.exception.BaseException;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.dao.model.Role;
import com.runfast.paotui.utils.JiGuangPushUtil;
import com.runfast.waimai.dao.model.RunfastPicture;
import com.runfast.waimai.dao.model.RunfastPictureExample;
import com.runfast.waimai.dao.model.RunfastPictureclass;
import com.runfast.waimai.dao.model.RunfastPictureclassExample;
import com.runfast.waimai.service.RunfastPictureService;
import com.runfast.waimai.service.RunfastPictureclassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Created by Ptkc on 2018/7/16 16:08.
 */
@Slf4j
@RestController
@RequestMapping("/server/picture")
public class PictureController {
    @Autowired
    private RunfastPictureService runfastPictureService;
    @Autowired
    private RunfastPictureclassService runfastPictureclassService;

    /*
     * 图片分类管理
     */
    //查询全部分类
    @GetMapping("/allClass")
    public Result allClass(){
        RunfastPictureclassExample pictureClassExample = new RunfastPictureclassExample();
        RunfastPictureclassExample.Criteria criteria = pictureClassExample.createCriteria();
        criteria.andIsdeleteNotEqualTo(0);
        criteria.andParentidIsNull();
        List<RunfastPictureclass> pictureClassList = runfastPictureclassService.selectByExample(pictureClassExample);
        Integer total = runfastPictureclassService.countByExample(pictureClassExample);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",pictureClassList);
        map.put("total",total);
        return Result.ok(null, map);
    }

    //添加分类
    @PostMapping("/save")
    public Result SaveClass(@RequestBody RunfastPictureclass pictureclass){
        if(pictureclass.getName()==null)
            return Result.fail(null,"分类名称不能为空");
        pictureclass.setCreatetime(new Date());
        pictureclass.setIsdelete(1);
        runfastPictureclassService.insertSelective(pictureclass);
        return Result.ok("保存成功");
    }

    //修改分类
    @PostMapping("/update")
    public Result updateClass(@RequestBody RunfastPictureclass pictureclass){
        if(pictureclass.getName()==null)
            return Result.fail(null,"分类名称不能为空");
        if(pictureclass.getId()==null)
            return Result.fail(null,"id为空");
        pictureclass.setCreatetime(new Date());
        runfastPictureclassService.updateByPrimaryKeySelective(pictureclass);
        return Result.ok("修改成功");
    }

    //删除分类
    @PostMapping("/delete")
    @Transactional(rollbackFor = BaseException.class)
    public Result deleteClass(@RequestBody RunfastPictureclass pictureclass){
        if(pictureclass.getId()==null)
            return Result.fail(null,"id为空");
        runfastPictureclassService.updateDeleteStatus(pictureclass);//改变子分类的删除状态
        RunfastPictureclassExample pictureClassExample = new RunfastPictureclassExample();
        RunfastPictureclassExample.Criteria criteria = pictureClassExample.createCriteria();
        criteria.andParentidEqualTo(pictureclass.getId());
        criteria.andIsdeleteEqualTo(1);
        List<RunfastPictureclass> pictureClassList = runfastPictureclassService.selectByExample(pictureClassExample);
        if (!pictureClassList.isEmpty() && pictureClassList!=null){
            RunfastPictureclass a = new RunfastPictureclass();
            for (RunfastPictureclass list:pictureClassList){
                a.setId(list.getId());
                a.setIsdelete(0);
                a.setCreatetime(new Date());
                runfastPictureclassService.updateDeleteStatus(a);//如果有子分类，将改变子分类的删除状态
            }
        }
        return Result.ok("删除成功");
    }

    /*
    * 图片管理
    */
    //根据条件查询图片
    @GetMapping("/allPicture")
    public Result allPicture(@PageableDefault Pageable pageable, RunfastPicture runfastPicture, String beginTime, String endTime){
        RunfastPictureExample pictureExample = new RunfastPictureExample();
        RunfastPictureExample.Criteria criteria = pictureExample.createCriteria();
        //pictureExample.setOrderByClause("sort desc");
        Date beginTimer;
        Date endTimer;
        if(beginTime!=null && beginTime!="" && endTime!=null && endTime!=""){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                beginTimer = sdf.parse(beginTime);
                endTimer = sdf.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
                return Result.fail(ResultCode.PARAMETER_ERROR, "日期格式错误");
            }
            criteria.andCreatetimeBetween(beginTimer, endTimer);
        }
        Integer typeId = runfastPicture.getTypeid();
        if(typeId!=null){
            //criteria.andTypeidEqualTo(runfastPicture.getTypeid());
            List<Integer> typeIds = new ArrayList<Integer>();
            typeIds.add(typeId);
            RunfastPictureclassExample pictureclassExample = new RunfastPictureclassExample();
            pictureclassExample.createCriteria().andParentidIsNotNull().andParentidEqualTo(typeId);
            List<RunfastPictureclass> list = runfastPictureclassService.selectByExample(pictureclassExample);
            if(list!=null){
                for (RunfastPictureclass pic:list){
                    typeIds.add(pic.getId());
                }
            }
            criteria.andTypeidIn(typeIds);
        }
        criteria.andIsdeleteNotEqualTo(0);
        if (runfastPicture.getIntroduction()!=null && runfastPicture.getIntroduction().trim()!="")
            criteria.andIntroductionLike("%" + runfastPicture.getIntroduction() + "%");
        List<RunfastPicture> list = runfastPictureService.selectByExampleWithPageable(pictureExample, pageable);
        List<RunfastPictureclass> pictureClassList = runfastPictureclassService.selectByExample(null);
        for(RunfastPicture picture:list){
            for(RunfastPictureclass pictureClass:pictureClassList){
                if(picture.getTypeid()==pictureClass.getId())
                    picture.setTypename(pictureClass.getName());
            }
        }
        Integer total = runfastPictureService.countByExample(pictureExample);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null, map);
    }

    @GetMapping("/picture")
    //根据id或Name获取图片
    public Result picture(Integer typeId, String typeName){
        List<Integer> typeIds = new ArrayList<Integer>();
        if (typeName != null) {
            RunfastPictureclassExample pictureClassExample = new RunfastPictureclassExample();
            RunfastPictureclassExample.Criteria criteriaClass = pictureClassExample.createCriteria();
            criteriaClass.andNameEqualTo(typeName);
            List<RunfastPictureclass> pictureClassList = runfastPictureclassService.selectByExample(pictureClassExample);
            if (pictureClassList != null && !pictureClassList.isEmpty()) {
                for (RunfastPictureclass pClass:pictureClassList){
                    typeIds.add(pClass.getId());
                }
            }
        }
        RunfastPictureExample pictureExample = new RunfastPictureExample();
        if(typeId!=null || !typeIds.isEmpty()){
            RunfastPictureExample.Criteria criteria = pictureExample.createCriteria();
            //criteria.andTypeidEqualTo(runfastPicture.getTypeid());
            typeIds.add(typeId);
            RunfastPictureclassExample pictureclassExample = new RunfastPictureclassExample();
            pictureclassExample.createCriteria().andParentidIsNotNull().andParentidEqualTo(typeId);
            List<RunfastPictureclass> list = runfastPictureclassService.selectByExample(pictureclassExample);
            if(list!=null && !list.isEmpty()){
                for (RunfastPictureclass pic:list){
                    typeIds.add(pic.getId());
                }
            }
            criteria.andTypeidIn(typeIds);
        }
        List<RunfastPicture> list = runfastPictureService.selectByExample(pictureExample);
        Integer total = runfastPictureService.countByExample(pictureExample);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok("", map);
    }

    @PostMapping("/addPicture")
    //添加图片
    public Result addPicture(@RequestBody RunfastPicture runfastPicture){
        if(runfastPicture.getImgpath()==null)
            return Result.fail(ResultCode.PARAMETER_ERROR, "图片为空");
        runfastPicture.setCreatetime(new Date());
        runfastPicture.setIsdelete(1);
        runfastPicture.setIsenable(1);
        runfastPicture.setSort(1);
        runfastPictureService.insertSelective(runfastPicture);
        return Result.ok("保存成功");
    }

    //修改图片
    @PostMapping("/updatePicture")
    public Result updatePicture(@RequestBody RunfastPicture runfastPicture){
        if(runfastPicture.getImgpath()==null)
            return Result.fail(ResultCode.PARAMETER_ERROR, "图片为空");
        if(runfastPicture.getId()==null)
            return Result.fail(ResultCode.PARAMETER_ERROR, "id为空");
        runfastPicture.setCreatetime(new Date());
        runfastPictureService.updateByPrimaryKeySelective(runfastPicture);
        return Result.ok("修改成功");
    }

    //删除图片
    @PostMapping("/deletePicture")
    public Result deletePicture(@RequestBody RunfastPicture runfastPicture){
        if(runfastPicture.getId()==null)
            return Result.fail(ResultCode.PARAMETER_ERROR, "id为空");
        runfastPicture.setCreatetime(new Date());
        runfastPicture.setIsdelete(0);
        runfastPictureService.updateByPrimaryKeySelective(runfastPicture);
        return Result.ok("删除成功");
    }

    //推送测试
    @GetMapping("/push")
    public Result push(){
        ArrayList<String> aliases = new ArrayList();
        aliases.add("865629033792334");
        /*aliases.add("868403035690038");
        aliases.add("B96D85B561A14B66967D2A4521E1F22D");
        aliases.add("863387031474098");
        aliases.add("868918031879277");
        aliases.add("862391030653042");
        aliases.add("4E773233CABB47DC91F4EC6EC6D35456");*/
        /*aliases.add("1507bfd3f7e1733d9b8");
        aliases.add("190e35f7e07a6a1a7dd");*/
        HashMap<String, String> params = new HashMap<>();
        params.put("orderNo", "justTest");
        PushResult pushResult = JiGuangPushUtil.push(Role.Predefine.DRIVER, 600, aliases, "Can you get the Message!!!", params, "neworder.caf");
        if (!pushResult.isResultOK()) {
            StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[1];
            return Result.fail(null,"失败");
        }else
            return Result.ok("成功");
    }
}
